package com.example.a10928.weifriend.util;

import android.content.Context;
import android.databinding.ObservableBoolean;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.example.a10928.weifriend.http.configuration.ApiException;
import com.example.a10928.weifriend.http.configuration.CodeErrorShowException;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.List;

import static android.view.View.GONE;


public class Utils {

    private static Context context;
//    private static boolean isNetWork;
    public static ObservableBoolean isNetWork = new ObservableBoolean();

    private Utils() {
        throw new UnsupportedOperationException("u can't instantiate me...");
    }

    /**
     * 初始化工具类
     * @param context 上下文
     */
    public static void init(Context context) {
        Utils.context = context.getApplicationContext();
    }

    /**
     * 获取ApplicationContext
     * @return ApplicationContext
     */
    public static Context getContext() {
        if (context != null) return context;
        throw new NullPointerException("u should init first");
    }

    public static void error(Exception e) {
        if (e instanceof ApiException)
            CodeErrorShowException.show(((ApiException) e).getCode(), ((ApiException) e).getMsg());
    }

    /**
     * 根据手机分辨率从DP转成PX
     * @param context
     * @param dpValue
     * @return
     */
    public static int dp2px(Context context, float dpValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public static <T> T gsonDataString(String data, Class<T> tClass) {
        return JSON.parseObject(data, tClass);
    }

    public static <T> List<T> gsonDataStringArray(String data, Class<T> tClass) {

        try {
            Object json = new JSONTokener(data).nextValue();

            if (json instanceof JSONObject) {
                JSONObject jsonObject = (JSONObject) json;
            } else if (json instanceof JSONArray) {
                JSONArray jsonArray = (JSONArray) json;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return JSON.parseArray(data, tClass);
    }

    public static ObservableBoolean getIsNetWork() {
        return isNetWork;
    }


}
